<template></template>

<script>
import {
  add,
  edit,
  list,
  remove,
  checkBeforeDelete,
  unbundedApp,
  querySystemNameList,
  queryList,
} from "@/api/apisecurity/applicationType/applicationType";

export default {
  name: "index",
  data() {
    return {
      isTypeEdit: false,
      isTypeDialog: false,
      dialogLoading: false,
      typeForm: {
        orgId: null,
        orgName: null,
        remark: null,
        parentId: null,
        status: 0,
        type: 0,
      },
      typeRule: {
        orgName: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      selectForm: null,
      orgId: null,
      businessSystemId: null,
      appId: null,
      defaultExpandedKeys: [],
    };
  },
  methods: {
    addType(info) {
      // this.currentNodeKey = info.orgId;
      this.isTypeDialog = true;
      this.isTypeEdit = false;
      this.typeForm.parentId = info.orgId;
    },
    editType(info) {
      // this.currentNodeKey = info.orgId;
      this.isTypeDialog = true;
      this.isTypeEdit = true;
      Reflect.ownKeys(this.typeForm).forEach(
        (k) => (this.typeForm[k] = info[k])
      );
    },
    resetForm() {
      this.typeForm = {
        orgId: null,
        orgName: null,
        remark: null,
        parentId: null,
        status: 0,
        type: 0,
      };
    },
    cancelTypeForm() {
      this.resetForm();
      this.isTypeDialog = false;
    },
    submitTypeForm() {
      this.$refs["typeForm"].validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          if (this.isTypeEdit) {
            edit(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.cancelTypeForm();
                  this.getApplicationList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg).then();
                }
              })
              .finally(() => (this.dialogLoading = false));
          } else {
            add(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.cancelTypeForm();
                  this.getApplicationList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg).then();
                }
              })
              .finally(() => (this.dialogLoading = false));
          }
        }
      });
    },

    handleDeleteTree(row) {
      // console.log(row);
      // this.currentNodeKey = row.orgId;
      if (row.type === "1") {
        this.$GlobalDeleteConfirm("是否确认解绑数据项？")
          .then(() => {
            unbundedApp({ appIdList: [row.orgId] }).then((res) => {
              if (res && res.code === 200) {
                this.getApplicationList();
                this.$GlobalSuccessMessage("解绑成功");
              } else {
                this.$GlobalErrorConfirm("解绑失败", res.msg).then();
              }
            });
          })
          .catch();
      } else {
        this.beforeDeleteForCheck(row.orgId)
          .then((res) => {
            this.$GlobalDeleteConfirm()
              .then(() => {
                remove({ orgId: row.orgId }).then((res) => {
                  if (res && res.code === 200) {
                    this.getApplicationList();
                    this.$GlobalSuccessMessage("解绑成功");
                  } else {
                    this.$GlobalErrorConfirm("解绑失败", res.msg).then();
                  }
                });
              })
              .catch();
          })
          .catch((err) => {
            this.$GlobalErrorConfirm("解绑失败", err.msg);
          });
      }
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        checkBeforeDelete({ orgId: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    addApplication(info) {
      // this.currentNodeKey = info.orgId;
      this.$refs.chooseMultiple.show(info.orgId);
    },

    refresh() {
      this.getApplicationList();
    },

    // -------------------------- 左侧应用管理树结构数据 --------------------------
    //设置树节点初始化高亮
    setHighLightShowTree(id) {
      this.$refs.treeRef.$refs.tree.setCurrentKey(id);
    },

    getApplicationList() {
      this.treeLoading = true;
      queryList()
        .then((res) => {
          if (res && res.code === 200) {
            this.applitionTreeData = res.data;
            this.defaultExpandedKeys = this.applitionTreeData.length
              ? [this.applitionTreeData[0].orgId]
              : [];
            // this.applitionTreeData = this.handleTree(data, "orgId");

            this.currentNodeKey = this.applitionTreeData.length
              ? this.applitionTreeData[0].orgId
              : null;
            this.orgId = this.currentNodeKey;

            this.$nextTick(() => {
              this.setHighLightShowTree(this.currentNodeKey);
            });
            // this.getList();
          } else {
            this.applitionTreeData = [];
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.treeLoading = false;
        });
    },
    // 树节点点击事件
    handleTreeNodeClick(info) {
      this.selectForm = info.data;
      this.orgId = info.data.type === "0" ? info.data.orgId : null;
      this.businessSystemId = info.data.type === "1" ? info.data.appId : null;
      this.appId = info.data.type === "2" ? info.data.appId : null;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.currentNodeKey = info.data.orgId;
      this.getList();
    },
    // 获取当前节点下面关联应用数量
    getApplicationNums(data, nums) {
      let number = nums || 0;
      if (data && data.length) {
        data.forEach((item) => {
          if (item.type === "1") number++;
          if (item.children) {
            number = this.getApplicationNums(item.children, number);
          }
        });
      }
      return number;
    },

    handleNodeExpand(nodeData) {
      if (nodeData.data.type === "1" && !nodeData.data.children.length) {
        nodeData.node.loading = true;
        querySystemNameList({ businessSystemId: nodeData.data.orgId })
          .then((res) => {
            if (res && res.code === 200 && res.data.length) {
              let children = res.data.reduce((r, c) => {
                if (!c.children || !c.children.length) {
                  delete c.children;
                }
                r.push(c);
                return r;
              }, []);

              this.$nextTick(() => {
                this.$refs.treeRef.$refs.tree.updateKeyChildren(
                  nodeData.data.orgId,
                  children
                );

                nodeData.node.childNodes.forEach((item) => {
                  item.isLeaf = true;
                });
              });
            } else {
            }
          })
          .finally(() => {
            nodeData.node.loading = false;
          });
      }
    },

    // 指定节点懒加载
    load(node, resolve) {
      if (node.level === 0) {
        return resolve([]);
      }

      if (node.data.type === "2") {
        return resolve([]);
      }

      if (node.data.type === "1") {
        // 此处自定义取得方法;
        let businessSystemId = node.data.orgId;
        querySystemNameList({ businessSystemId })
          .then((res) => {
            if (res && res.code === 200 && res.data.length) {
              node.data.children = res.data.reduce((r, c) => {
                if (!c.children || !c.children.length) {
                  delete c.children;
                }
                r.push(c);
                return r;
              }, []);
              return resolve(res.data);
            } else {
              node.loaded = false;
              node.expanded = false;
              // node.expand();
              return resolve();
            }
          })
          .catch((err) => {
            node.loaded = false;
            node.expanded = false;
            // node.expand();
            // return resolve();
          });
      } else {
        // 已取得子节点
        if (node.data.children && node.data.children.length) {
          return resolve(node.data.children);
        } else {
          node.loaded = false;
          node.loading = false;
          // return resolve();
        }
      }
    },
  },
};
</script>

<style scoped></style>
